﻿using System;
using System.Data.Entity.Validation;
using System.Text;
using log4net;

//using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace Lari.Services.Utility
{
    public static class LogServiceHelper
    {
        private static readonly ILog Ilog = LogManager.GetLogger("LariLogger");

        private static string FormatExecption(Exception e)
        {
            return FormatExecption(e, string.Empty);
        }

        private static string FormatExecption(Exception e, string exceptionMessage)
        {
            if (e == null) return string.Empty;

            exceptionMessage = string.Format(
                "{0}\n{1}{2}\n{3}",
                exceptionMessage,
                (exceptionMessage == string.Empty) ? string.Empty : "\n",
                e.Message,
                e.StackTrace);

            if (e.InnerException != null)
                exceptionMessage = FormatExecption(e.InnerException, exceptionMessage);
           
            var sb = new StringBuilder();

            if (e is DbEntityValidationException)
            {
                
                var efError = e as DbEntityValidationException;
                foreach (var validation in efError.EntityValidationErrors)
                {
                    foreach (var err in validation.ValidationErrors)
                    {
                        sb.Append("Entity Errors - " + err.ErrorMessage + " for column " + err.PropertyName+"\n");
                    }
                    
                }
            }
          
            return exceptionMessage + "\n" + sb.ToString();
        }

        public static void WriteErrorLog(string errorMessage, Exception ex, string module)
        {
             string msg = FormatExecption(ex,errorMessage);
                GlobalContext.Properties["Module"] = module;
                GlobalContext.Properties["Exception"] = ex;
                GlobalContext.Properties["ErrorCode"] = errorMessage;
                Ilog.Error(msg);
           
        }
    }
}